import axios from 'axios'
import { msg } from '@/common/js/util'
// 联调环境使用dev的BASE_API，所有打包配置都用用户访问项目的ip地址
// const BASE_IP = 'http://localhost:8188/'
const BASE_IP = process.env.NODE_ENV === 'development' ? 'http://192.168.1.7:8188/' : `${location.origin}/` // 吉林sit环境
const PREFIX = ''

// create an axios instance
const service = axios.create({
  baseURL: BASE_IP + PREFIX,
  // baseURL: process.env.BASE_API,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Accept'] = 'application/json, application/octet-stream'
    config.headers['Content-Type'] = 'application/json'
    config.headers['X-access-token'] = uni.getStorageSync("token")
    return config
  },
  error => {
    // do something with request error
    //  console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const status = response.status
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res && status === 200) {
      const { code, message } = res
      return res
    }
  },
  error => {
    const errorRes = error.response
    console.log('error:', JSON.stringify(error));
    if (errorRes) {
      const { status, data: { message } } = errorRes
      msg(message+'-'+status)
      console.log('isIncluedes:', message.includes('登录已过期'));
      if (message.includes('登录已过期')){
        uni.navigateTo({
          url: `/pages/auth/login`,
        });
      }
    } else {
      msg('网络错误！！！')
    }
    return Promise.reject(error)
  }
)

export default service;
